<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace api\user\controller;

use cmf\controller\RestUserBaseController;
use think\Db;
use think\Validate;

//项目控制器
class ProjectController extends RestUserBaseController
{
    // 获取项目表列表的;
    public function index()
    {
        $data = $this->request->param();

        $where = '';
        $projectType = '';
        if (!empty($data['search'])) {
            $search = $data['search'];
            $where['company_name']   = ['like', "%$search%"];
        }

        if (!empty($data['type_id'])) {
            $projectType['project_type_id'] = $data['type_id'];
        }

        //获取当前用户角色
        $role = $this->getUserRole();
        $userId = $this->getUserId();
        switch ($role) {
            case '业务员':
                $where['yewu_id'] = $userId;
                break;
            case '技术员':
                $where['jishu_id'] = $userId;
                break;
            case '审核员':
                $where['status'] = ['in', [3,4,5]];
                $where['shenhe_id'] = $userId;
                break;
            default:
                $where = [];
                break;
        }

        $project_data = Db::name('project')
            ->alias('p')
            ->join('__PROJECT_TYPE__ t','t.id = p.project_type_id')
            ->join('__USER__ u','p.yewu_id = u.id')
            ->field('p.*, t.name, u.user_nickname')
            ->whereOr($projectType)
            ->where($where)
            ->order('status')
            ->select()
            ->toArray();

        $type = [0 => '申请中', 1=>'分配中', 2=>'修改中', 3=>'审核中', 4=>'已完成', 5=>'审核不通过'];
        foreach ($project_data as &$vo) {
            $vo['year'] = date('Y', $vo['create_time']);
            $vo['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
            $vo['type_status'] = $type[$vo['status']];
            //查询技术员名称
            if ($vo['jishu_id']) {
                $jishu = Db::name("user")->field('user_nickname')->where('id', $vo['jishu_id'])->find();
                $vo['jishu'] = $jishu['user_nickname'];
            } else {
                $vo['jishu'] = '未分配';
            }
            //查询审核员名称
            if ($vo['shenhe_id']) {
                $jishu = Db::name("user")->field('user_nickname')->where('id', $vo['shenhe_id'])->find();
                $vo['shenhe'] = $jishu['user_nickname'];
            } else {
                $vo['shenhe'] = '未分配';
            }
        }
        unset($vo);

        ////////////////////////////////////我时分割线xue改的代码//////////////////////////////////////////////////////////////
        //合并相同的名字一个数组
        $result= array();
        foreach ($project_data as $key => $info) {
            $result[$info['company_name']][] = $info;
        }


        foreach ($result as $key => &$value) {
            // code...
            $row = count($value);
            foreach ($value as $k => &$v) {
                // code...
                $v['row'] = $row;
                $row = $row-$row;
            }
        }
        unset($value);
        unset($k);


        $new_array = [];

        foreach ($result as $key1=>$vv) {
            foreach ($vv as $value1) {
                array_push($new_array, $value1);
            }
        }

        $project_data = $new_array;


        //然后通过一个新数组把他解开，

        ////////////////////////////////////我时分割线//////////////////////////////////////////////////////////////

        //统计项目数量
        $count = count($project_data);

        //获取切割次数
        $offset = ceil(count($project_data) / 10);

        // 切割数组
        for ($i=0; $i < $offset; $i++) {
            $data[$i] = array_slice($project_data, $i*10, 10);
        }

        $this->success("查询企业项目成功!",['project_data'=>$data, 'count'=>$count]);

    }



    /**
     * 首页待办事件
     */
    public function agentEvent()
    {
        $data = $this->request->param();

        //获取当前用户角色
        $role = $this->getUserRole();
        $userId = $this->getUserId();
        switch ($role) {
            case '业务员':
                $where['status'] = ['in', [0,4]];
                $where['yewu_id'] = $userId;
                break;
            case '管理员':
                $where['status'] = ['in', [1,4]];
                break;
            case '技术员':
                $where['status'] = ['in', [2,4,5]];
                $where['jishu_id'] = $userId;
                break;
            case '审核员':
                $where['status'] = ['in', [3,4]];
                $where['shenhe_id'] = $userId;
                break;
            default:
                # code...
                break;
        }

        $project_data = Db::name('project')
            ->alias('p')
            ->join('__PROJECT_TYPE__ t','t.id = p.project_type_id')
            ->join('__USER__ u','p.yewu_id = u.id')
            ->field('p.*, t.name, u.user_nickname')
            ->where($where)
            ->order('status')
            ->select()
            ->toArray();


        $this->success("获取待办项目列表成功!",$project_data);
    }



    /**
     * 根据角色获取用户列表
     */
    public function getRoleUserList()
    {
        $data = $this->request->param();
        if (empty($data['name'])) {
            $this->error("参数错误!");
        }

        $where['name'] = $data['name'];
        //查询审核员的角色ID
        $roleId = Db::name("role")->where($where)->find();
        $user = Db::name("role_user")
                                ->alias('r')
                                ->join('__USER__ u','r.user_id = u.id')
                                ->field('u.id, u.user_nickname')
                                ->where('role_id', $roleId['id'])
                                ->select()
                                ->toArray();

        $this->success('获取成功!', $user);
    }






    /**
     * 根据ID获取项目信息
     */
    public function getProject()
    {
        $id = $this->request->param('id');
        if (empty($id)) {
            $this->error("参数错误!");
        }

        $where['p.id'] = $id;

        $project_data = Db::name('project')
            ->alias('p')
            ->join('__PROJECT_TYPE__ t','t.id = p.project_type_id')
            ->join('__USER__ u','p.yewu_id = u.id')
            ->field('p.*, t.name, u.user_nickname')
            ->where($where)
            ->find();

        $type = [0 => '申请中', 1=>'分配中', 2=>'修改中', 3=>'审核中',4=>'已完成', 4=>'审核不通过'];

        $project_data['year'] = date('Y', $project_data['create_time']);
        $project_data['create_time'] = date('Y-m-d H:i:s', $project_data['create_time']);
        $project_data['type_status'] = $type[$project_data['status']];

        $this->success("查询企业项目成功!", $project_data);
    }






    /**
     * 给项目添加人员管理
     */
    public function saveManage()
    {
        $role = $this->getUserRole();

        if ($role != '管理员') {
            $this->error("你没有权限进行此操作!");
        }

        $data = $this->request->param();

        if (empty($data['id'])) $this->error("参数错误!");

        $validate = new Validate([
            'jishu_id'      => 'require',
            'shenhe_id'     => 'require',

        ]);

        $validate->message([
            'jishu_id.require'     => '请选择技术人员!',
            'shenhe_id.require'     => '请选择审核人员!',
        ]);

        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $id = $data['id'];

        $result = Db::name("project")->where('id', $id)->update(['jishu_id' => $data['jishu_id'], 'shenhe_id' => $data['shenhe_id'], 'status' => 2]);

        if (empty($result)) {
            $this->error("分配人员失败，请重试!");
        }

        $this->success("分配人员成功!");
    }



    /**
     * 处理人员填写完项目资料进行提交
     */
    public function submit()
    {
        $id = $this->request->param('id');

        if (!$id) $this->error("参数错误!");

        //查看是哪个角色的人员提交的
        $role = $this->getUserRole();

        switch ($role) {
            case '业务员':
                $result = Db::name("project")->where('id', $id)->update(['status'=>1]);
                break;
            case '管理员':
                $result = Db::name("project")->where('id', $id)->update(['status'=>2]);
                break;
            case '技术员':
                $result = Db::name("project")->where('id', $id)->update(['status'=>3]);
                break;
            default:
                $this->error("错误操作!");
                break;
        }

        if (empty($result)) {
            $this->error("提交失败，请重试!");
        }

        $this->success("提交成功!");
    }



    /**
     * 处理审核员审核完成后进行项目审核
     */
    public function check()
    {
        $role = $this->getUserRole();

        if ($role != '审核员') $this->error("你没有权限进行此操作!");

        $id = $this->request->param('id');
        $status = $this->request->param('status');

        if (!$id) $this->error("参数错误!");
        if (empty($status)) $this->error("参数错误!");

        if ($status == 1) {
            //审核通过
            $result = Db::name("project")->where('id', $id)->update(['status'=>4]);
        } else if ($status == 2) {
            //审核不通过
            $result = Db::name("project")->where('id', $id)->update(['status'=>5]);
        }

        if (empty($result)) $this->error("审核失败!");

        $this->success("审核成功!");
    }

}
